package com.code.demo.ui.common;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.code.demo.R;
import com.code.demo.ui.base.BaseActivity;


public class DialogLoading {

    private Activity activity;
    public Dialog mDialog;
    private AnimationDrawable animationDrawable = null;
    private TextView text;


    public DialogLoading(Activity avt, String message) {

        this.activity = avt;

        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.widget_dialog_loading, null);

//        text = (TextView) view.findViewById(R.id.progress_message);
//        text.setText(message);
        ImageView loadingImage = (ImageView) view.findViewById(R.id.progress_view);
        Animation rotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.loading);
        loadingImage.startAnimation(rotateAnimation);

        mDialog = new Dialog(activity, R.style.dialogLoading);
        mDialog.setContentView(view);
        mDialog.setCanceledOnTouchOutside(false);

    }

    public void setMessage(String message) {
        text.setText(message);
    }

    public void show() {
        if (animationDrawable != null) {
            animationDrawable.setOneShot(false);
            animationDrawable.start();
        }
        mDialog.show();
    }

    public void showTimeout(long ms) {
        mDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dismiss();
            }
        }, ms);
    }

    public void setCanceledOnTouchOutside(boolean cancel) {
        mDialog.setCanceledOnTouchOutside(cancel);
    }

    public void dismiss() {
        if (mDialog.isShowing()) {
            if (animationDrawable != null) {
                animationDrawable.stop();
            }
            mDialog.dismiss();
        }
    }

}
